<template>
    <search-table
            ref="selectTable"
            :columns="columns"
            :data="bindCameraList"
            :total="total"
            :page.sync="pageIndex"
            :size.sync="pageSize"
            showSelectTag
            selectKey="cameraId"
            selectName="cameraName"
            :selection.sync="selectCameras"
            @queryFun="getBindCameraList">
            <!-- <template slot="checkbox-group">
                <Checkbox v-model="selectAll" :disabled="bindCameraList.length === 0 || disabledAllBtn" @on-change="selectAllChange">全选</Checkbox>
            </template> -->
            <template slot="button-group">
                <Button
                    type="primary"
                    ghost
                    @click="showModal = true"
                    :disabled="disabledAllBtn"
                    icon="md-add">绑定摄像头</Button>
                <Poptip 
                    confirm 
                    title="你确定要移除选中的摄像头吗？"
                    transfer
                    @on-ok="batchesDelete">
                    <Button
                        type="error"
                        ghost
                        :disabled="selectCameras.length === 0 || disabledAllBtn"
                        icon="ios-trash-outline">批量移除</Button>
                </Poptip>
                <Poptip 
                    confirm 
                    title="你确定要全部启动吗？"
                    transfer
                    @on-ok="pushCameraDataByTask('start')">
                    <Button
                        type="primary"
                        ghost
                        :disabled="bindCameraList.length === 0 || disabledAllBtn || loading"
                        icon="ios-play">全部启动</Button>
                </Poptip>
                <Poptip 
                    confirm 
                    title="你确定要全部停止吗？"
                    transfer
                    @on-ok="pushCameraDataByTask('stop')">
                    <Button
                        type="primary"
                        ghost
                        :disabled="bindCameraList.length === 0 || disabledAllBtn || loading"
                        icon="ios-pause">全部停止</Button>
                </Poptip>
                <Button
                    type="primary"
                    ghost
                    @click="showDrawer = true"
                    icon="ios-options">摄像头管理</Button>
            </template>
            <template slot="input-group">
                <Input v-model.trim="cameraName" placeholder="请输入摄像头名称" />
            </template>
        <Drawer title="摄像头管理" v-model="showDrawer" :width='100'>
            <camera-list v-if="showDrawer"></camera-list>
        </Drawer>
        <Modal
            v-model="showModal"
            width="800"
            title="绑定摄像头">
            <Transfer
                class="transfer"
                :data="cameraList"
                :target-keys="targetKeys"
                filterable
                :filter-method="filterMethod"
                @on-change="handleChange"></Transfer>
            <div slot="footer" class="footer">
                <Button type="text" size="large" @click="showModal = false">取消</Button>
                <Button type="primary" size="large" @click="showModal = false">确定</Button>
            </div>
        </Modal>
    </search-table>
</template>

<script>
    import SearchTable from '@/components/SearchTable/SearchTable'
    import CameraList from '@/view/drill_compete/page/camera-list'
    import { getBindCameraList, bindCamera, unbindCamera, getCameraList, pushCameraData, pushCameraDataByTask } from '@/api/cameras'

    export default {
        name: 'BindCamera',
        components: {
            SearchTable,
            CameraList
        },
        props: {
            disabledAllBtn: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                cameraName: '', // 搜索条件，摄像头名称
                loading: false,
                selectAll: false,
                showModal: false, // 显示绑定摄像头的模态框
                showDrawer: false, // 显示摄像头管理的抽屉
                selectCameras:[],
                total: 0, // 总数据量
                pageSize: 10, // 分页大小
                pageIndex: 1, // 当前页
                columns: [
                    {
                        type:'selection',
                        width:60,
                    },
                    {
                        placement: 'top-left',
                        title: '摄像头名称',
                        key: 'cameraName',
                        align: 'center',
                        tooltip: true,
                        width: 230
                    },
                    {
                        title: '摄像头访问地址',
                        width: 300,
                        key: 'accessPath',
                        tooltip: true
                    },
                    {
                        title: '创建时间',
                        width: 140,
                        key: 'createTime'
                    },
                    {
                        title: '设备状态',
                        width: 140,
                        key: 'status',
                        render:(h,params) => {
                            let status = params.row.status
                            return h('Tag', {
                                props:{
                                    color: status === 0 ? 'var(--status-no)' : 'var(--status-yes)'
                                }, 
                            }, status === 0 ? '离线' : '在线')
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 300,
                        opList: [
                            {
                                txt: '启动',
                                tooltip: true,
                                title: '你确定要启动吗？',
                                disabled: (data) => {
                                    return data.status !== 0 || this.disabledAllBtn;
                                },
                                fun: (data) => {
                                    this.pushCameraData(data.cameraId, 'start');
                                }
                            },
                            {
                                txt: '停止',
                                tooltip: true,
                                type: 'delete',
                                title: '你确定要停止吗？',
                                disabled: (data) => {
                                    return data.status === 0 || this.disabledAllBtn;
                                },
                                fun: (data) => {
                                    this.pushCameraData(data.cameraId, 'stop');
                                }
                            },
                            {
                                txt: '删除',
                                type: 'delete',
                                tooltip: true,
                                title: '你确定要删除吗？',
                                disabled: (data) => {
                                    return this.disabledAllBtn;
                                },
                                fun: (data) => {
                                    this.unbindCamera([data.cameraId], '', true)
                                }
                            }
                        ]
                    },
                    {
                        title:'操作',
                        key:'action1',
                        placement:'top-right',
                        show:false,
                        render:(h,params) => {
                            return h('div',[
                                h('Poptip', {
									props: {
										confirm: true,
										type: 'error',
										size: 'large',
										title: '你确定要启动吗？',
										transfer:true
									},
									on: {
										'on-ok': () => {
                                            this.pushCameraData(params.row.cameraId, 'start')
										}
									}
								}, [
									h('Button', {
										props: {
											type: 'primary',
											size: 'small',
                                            disabled: params.row.status !== 0 || this.disabledAllBtn
										},
										style: {
											marginRight: '5px'
										},
									}, '启动')
								]),
                                h('Poptip', {
									props: {
										confirm: true,
										type: 'error',
										size: 'large',
										title: '你确定要停止吗？',
										transfer:true
									},
									on: {
										'on-ok': () => {
                                            this.pushCameraData(params.row.cameraId, 'stop')
										}
									}
								}, [
									h('Button', {
										props: {
											type: 'primary',
											size: 'small',
                                            disabled: params.row.status === 0 || this.disabledAllBtn
										},
										style: {
											marginRight: '5px'
										},
									}, '停止')
								]),
                                h('Poptip', {
									props: {
										confirm: true,
										'ok-text': "确定",
										'cancel-text': "取消",
										type: 'error',
										size: 'large',
										title: '你确定要移除吗?',
										transfer:true
									},
									on: {
										'on-ok': () => {
											this.unbindCamera([params.row.cameraId], '', true)
										}
									}
								}, [
									h('Button', {
										props: {
											type: 'error',
											size: 'small',
                                            disabled:this.disabledAllBtn
										},
										style: {
											marginRight: '5px'
										},
									}, '移除')
								])
                            ])
                        }
                    }
                ],
                cameraList: [], // 摄像头列表
                targetKeys: [], // 全部已绑定的摄像头的主键
                bindCameraList: [] // 分页获取已绑定的摄像头列表
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.getBindCameraList()
            })
        },
        computed: {
           
        },
        methods: {
            // 推送竞赛下所有摄像头的状态
            pushCameraDataByTask(operation) {
                this.loading = true
                pushCameraDataByTask(this.$route.query.id, operation).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        this.$Message.info('推送指令成功')
                        clearTimeout(this.timer)
                        this.timer = setTimeout(() => {
                            this.getBindCameraList()
                        }, 2000)
                    }
                }).catch((e) => {
                    this.$Message.error('推送摄像头异常')
                }).finally(() => {
                    this.loading = false
                })
            },
            // 推送摄像头的状态
            pushCameraData(cameraId, operation) {
                pushCameraData(cameraId, operation).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        this.$Message.info(`${operation === 'start' ? '启动' : '停止'}摄像头成功`)
                        clearTimeout(this.timer)
                        this.timer = setTimeout(() => {
                            this.getBindCameraList()
                        }, 2000)
                    }
                }).catch(() => {
                    this.$Message.error('推送摄像头异常')
                })
            },
            // 处理穿梭框数据变化的方法
            handleChange (targetKeys, direction, moveKeys) {
                if (direction === 'right') {
                    this.bindCamera(targetKeys)
                } else {
                    this.unbindCamera(moveKeys, targetKeys)
                }
            },
            // 绑定摄像头
            bindCamera(cameraIds) {
                bindCamera(this.$route.query.id, cameraIds).then(({ code, message }) => {
                    if (code !== 1) {
                        this.Message.warning(message)
                    } else {
                        this.$Message.info('绑定摄像头成功')
                        this.targetKeys = cameraIds
                        this.cameraName = ''
                        this.getBindCameraList(1)
                    }
                }).catch(() => {
                    this.$Message.error('绑定摄像头异常')
                })
            },
            // 解绑摄像头
            unbindCamera(moveKeys, targetKeys, isSingle) {
                unbindCamera(this.$route.query.id, moveKeys).then(({ code, message }) => {
                    if (code !== 1) {
                        this.Message.warning(message)
                    } else {
                        this.$Message.info('解绑摄像头成功')
                        if (isSingle) {
                            this.pageIndex = (this.bindCameraList.length == 1 && this.pageIndex > 1) 
                                ? this.pageIndex - 1 
                                : this.pageIndex
                            this.$refs.selectTable.delSelectItem(moveKeys[0]);
                        }
                        this.targetKeys = targetKeys
                        this.getBindCameraList(1)
                    }
                }).catch(() => {
                    this.$Message.error('解绑摄像头异常')
                })
            },
            // 批量移除摄像头
            batchesDelete() {
                let cameraIds = this.selectCameras.map(item => item.cameraId);
                unbindCamera(this.$route.query.id, cameraIds).then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        // 移除后展示当前页，当前页没有数据展示前一页
                        this.pageIndex = (this.bindCameraList.length == cameraIds.length && this.pageIndex > 1) 
                            ? this.pageIndex - 1 
                            : this.pageIndex
                        this.selectCameras = [];
                        this.getBindCameraList()
                        this.$Message.info('批量移除摄像头成功')
                        this.selectAll = false
                    }
                }).catch(() => {
                    this.$Message.error('批量移除摄像头异常')
                })
            },
            // 穿梭框过滤方法
            filterMethod (data, query) {
                return data.label.indexOf(query) > -1
            },
            // 获取绑定的摄像头数据
            getBindCameraList(pageNow) {
                this.pageIndex = pageNow || this.pageIndex
                getBindCameraList({
                    taskId: this.$route.query.id,
                    pageIndex: this.pageIndex, 
                    pageSize: this.pageSize,
                    cameraName: this.cameraName
                }).then(({ code, data, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        this.total = data.count || 0
                        this.bindCameraList = data.list || []
                        this.selectAll = false // 每次刷新数据后，重置全选
                    }
                }).catch(() => {
                    this.$Message.error('查询绑定的摄像头异常')
                })
            }
        },
        watch: {
            showModal(val) { // 显示模态框时获取摄像头列表，及其已经绑定的摄像头列表
                if (val) {
                    let pageIndex = 1, pageSize = 2147483646
                    getCameraList({
                        pageIndex,
                        pageSize
                    }).then(({ code, data, message }) => {
                        if (code !== 1) {
                            this.$Message.warning(message)
                        } else {
                            this.cameraList = (data.list || []).map(item => {
                                return {
                                    key: item.cameraId,
                                    label: item.cameraName
                                }
                            })
                        }
                    }).catch(() => {
                        this.$Message.error('查询摄像头异常')
                    })
                    getBindCameraList({
                        taskId: this.$route.query.id,
                        pageIndex, 
                        pageSize
                    }).then(({ code, data, message }) => {
                        if (code !== 1) {
                            this.$Message.warning(message)
                        } else {
                            this.targetKeys = (data.list || []).map(item => item.cameraId)
                        }
                    }).catch(() => {
                        this.$Message.error('查询绑定的摄像头异常')
                    })
                }
            },
            cameraName() { // 摄像头名称改变时，重新获取首页数据
                clearTimeout(this.timer)
                this.timer = setTimeout(() => {
                    this.getBindCameraList(1)
                }, 200)
            },
        },
        beforeDestroy(){
            clearTimeout(this.timer)
        }
    }
</script>

<style scoped>
    .transfer {
        width: 100%;
        height: 300px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .transfer /deep/ .ivu-transfer-list {
        width: calc(50% - 20px);
        height: 100%;
    }
</style>